package yl.hs.bmipfull.utils.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import yl.hs.bmipfull.annotations.DBTable;
import yl.hs.bmipfull.pojo.flow.FlowInfoEntity;
import yl.hs.bmipfull.service.flow.IFlowDataService;
import yl.hs.bmipfull.service.flow.IFlowInfoService;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.FlowInfoState;

import java.util.Map;

/**
 * @author 张凯
 * @apiNote 流程数据处理切面
 * @since: 21-6-28 下午 6:08 创建
 */
@Slf4j
@Aspect
@Component
public record SaveDataAspect(IFlowDataService flowDataService, IFlowInfoService flowInfoService) {


    /**
     * 定义一个插入切点
     */
    @Pointcut(value = "execution(* yl.hs.bmipfull.daos.*.*.insertNew(..))")
    public void installPoint() {
    }

    /**
     * 定义一个插入切点
     */
    @Pointcut(value = "execution(* yl.hs.bmipfull.daos.*.*.update(..))")
    public void updatePoint() {
    }

    @AfterReturning(value = "installPoint()", returning = "returnValue")
    public void installAfterReturning(JoinPoint joinPoint, Object returnValue) {
        // 判断值是否已经保存成功
        if (returnValue instanceof Integer) {
            if ((Integer) returnValue > 0) {
                //获取参数
                Object[] args = joinPoint.getArgs();

                for (Object arg : args) {
                    Class<?> aClass = arg.getClass();
                    //Map<String, Object> map = Tl.toMap(arg);
                    DBTable dbTable = aClass.getAnnotation(DBTable.class);
                    if (dbTable != null) {
                        //判断当前数据类型是否能启动流程
                        String mapCode = dbTable.mapCode();
                        FlowInfoEntity flowInfo = flowInfoService.findByDataTypeAndState(mapCode, FlowInfoState.Enable.code);
                        if (flowInfo != null) {
                            try {
                                flowDataService.startFlow(flowInfo, arg);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }

    @AfterReturning(value = "updatePoint()", returning = "returnValue")
    public void updateAfterReturning(JoinPoint joinPoint, Object returnValue) {
        installAfterReturning(joinPoint, returnValue);
    }

    private void saveGlobalSearchData(Object data) {

    }
}
